package com.example.ecmftlutil.controller;

import com.example.ecmftlutil.util.JsonToFtlUtils;
import com.example.ecmftlutil.util.ReadFileCommon;
import com.example.ecmftlutil.util.pdf.TemplateUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/form")
public class TestFtlController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${ftl.path}")
    private String PATH_VAL;

    @GetMapping("/ftl")
    public void getUser(String path, HttpServletResponse response) throws Exception {
        String classPath = StringUtils.isEmpty(path) ? PATH_VAL : PATH_VAL + "//" + path;
        String dataPath = classPath + "//data.txt";
        String filePath = classPath + "//file.ftl";
        String content = JsonToFtlUtils.toXmlByFtl(ReadFileCommon.readFileStr(dataPath, ReadFileCommon.CHARSE_UTF_8), ReadFileCommon.readFileStr(filePath, ReadFileCommon.CHARSE_UTF_8));
        response.setCharacterEncoding(ReadFileCommon.CHARSE_UTF_8);
        PrintWriter pw = response.getWriter();
        //content为输出到浏览器的内容
        pw.write(content);
    }

    @GetMapping("/pdf")
    public void pdf(String path, HttpServletResponse response) throws Exception {
        String classPath = StringUtils.isEmpty(path) ? PATH_VAL : PATH_VAL + "//" + path;
        String dataPath = classPath + "/data.txt";
        String filePath = classPath + "/file.ftl";
        logger.info("数据文件路径：{},FTL文件路径：{}。", dataPath, filePath);
        //获取业务数据
        String content = ReadFileCommon.readFileStr(dataPath, ReadFileCommon.CHARSE_UTF_8);
        Map<String, Object> map = new Gson().fromJson(content, new TypeToken<Map<String, Object>>() {
        }.getType());
        File file = new File(filePath);
        //整合ftl文件和业务数据
        content = TemplateUtil.freeMarkerRender(map, file.getName(), file.getParentFile().getPath());
        //生成PDF
        String pdfName = UUID.randomUUID().toString().replace("-", "") + ".pdf";
        String pdfFile = file.getParentFile().getPath() + "/" + pdfName;
        ByteArrayOutputStream outputStream = TemplateUtil.createPdf(content, pdfFile);

        // 使用response获取字节输出流
        ServletOutputStream out = response.getOutputStream();
        out.write(outputStream.toByteArray());
    }
}

